from scipy import *
from matplotlib import *
from pylab import *
from scipy.optimize import leastsq
"""
Example of curve fitting for
a1*exp(-k1*t) + a2*exp(-k2*t)
"""
def dbexpl(t,p):
    return(p[0]*exp(-p[1]*t) + p[2]*exp(-p[3]*t))
a1,a2 = 1.0, 1.0
k1,k2 = 0.05, 0.2
t=arange(0,100,0.1)
data = dbexpl(t,[a1,k1,a2,k2]) + 0.02*randn(len(t))

def residuals(p,data,t):
    err = data - dbexpl(t,p)
    return err
p0 = [0.5,1,0.5,1] # initial guesses
guessfit = dbexpl(t,p0)
pbest = leastsq(residuals,p0,args=(data,t),full_output=1)
bestparams = pbest[0]
cov_x = pbest[1]
print 'best fit parameters ',bestparams
print cov_x
datafit = dbexpl(t,bestparams)
plot(t,data,'x',t,datafit,'r',t,guessfit)
xlabel('Time')
title('Curve-fitting example')
grid(True)
show()


#I put here only the important bits of code and presume that you can import the data yourself (the x data is called position and the y data is called power).
#
#from scipy.optimize import leastsq
#from scipy.special import erfc
#from numpy import *
#
#...
#
#fit_fn = lambda params, x: params[0]*erfc(-sqrt(2)*(x - params[1])/params[2])
#err_fn = lambda params, x, y: fit_fn(params, x) - y
#param_guess = [ 1.03, 0.0250, 3.0e-3 ]
#param_new, success = leastsq(err_fn, param_guess[:], args=(position, power))


#from scipy import *
#from scipy.fftpack import fftshift
#from pylab import *
#x,y = meshgrid(r_[-3:3:100j], r_[-3:3:100j]);
#z = 3*(1-x)**2*exp(-x**2-(y+1)**2) - 10*(x/5-x**3-y**5)*exp(-x**2-y**2) -
#(1/3)*exp(-(x+1)**2-y**2);
#wav = io.read_array('wavdata');
#x1 = r_[1:wav.size+1]
#subplot(2,2,1);contour(x,y,z,25);grid(True);title('Simple 2D Contour Plot');
#subplot(2,2,2);contourf(x,y,z);title('Filled Contour');
#subplot(2,2,3);h=specgram(wav);title('Spectrogram');
#subplot(2,2,4);hist(randn(100));title('Histogram');
#show();
